<?php
/**
 * Created by PhpStorm.
 * User: ewen
 * Date: 2020-10-13
 * Time: 10:01
 */

namespace app\common\model;


use think\Db;
use think\Exception;

class XkSignRecord extends Common
{

    /**
     * 判断今日是否已经签到
     * @param $userID
     * @return int|string
     */
    public static function hasSigned($userID)
    {
        $where = [
            'userID' => $userID,
            'date' => currentDate()
        ];
        return self::where($where)->count();
    }

    /**
     * 获取上一次签到记录
     * @param $userID
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getLastSignRecord($userID)
    {
        $info = self::where([
            'userID' => $userID
        ])->order('date desc')->limit(1)->find();
        return $info;
    }

    /**
     * 新增签到记录
     * @param $userID
     */
    public static function addSignRecord($userID)
    {
        $hasSigned = self::hasSigned($userID);
        $hasSigned && backError(lang('already sign'));

        Db::startTrans();
        try {
            $addData = [
                'userID' => $userID,
                'date' => currentDate(),
                'addTime' => time()
            ];
            $lastRecordInfo = self::getLastSignRecord($userID);
            $realSignNum = $lastRecordInfo['realNum'];// 真实连续签到天数
            if ($lastRecordInfo) {
                //  判断昨日是否签到
                if ($lastRecordInfo['date'] == date('Y-m-d', strtotime('-1 day'))) {
                    $nowSignNum = $lastRecordInfo['num'] + 1;// 连续签到天数增加
                    $realSignNum++;// 真实连续签到天数增加
                } else {
                    //  断签，重新开始新的签到周期
                    $nowSignNum = 1;// 连续签到天数第一天
                    $realSignNum = 1;
                }

            } else {
                //  第一次签到
                $nowSignNum = 1;// 连续签到天数第一天
                $realSignNum = 1;
            }

            $addData['num'] = $nowSignNum;
            $addData['realNum'] = $realSignNum;
            //  新增签到记录
            $res = self::add($addData);
            if (!$res) throw new Exception(lang('sign failed'));

            //  获取签到TTUSD奖励
            $award = XkSystemRule::getAwardNum('sign');
            if ($award) {
                //  判断奖励是否溢出
                AssetFlow::getFlowTypeSumIncome($userID);
                $res = WebAssetAccount::coinAmountChange($userID, 'TXUSD', $award, self::TYPE_INC, 100);
                if ($res['status'] == 0) throw new Exception($res['msg']);
            }

            $backInfo = [
                'num' => $nowSignNum,
            ];

            Db::commit();
            backSuccess($backInfo, lang('sign successfully'));
        } catch (Exception $e) {
            Db::rollback();
            backError($e->getMessage());
        }
    }

    /**
     * 获取签到记录
     * @param $userID
     * @param int $per
     * @return array
     */
    public static function getUserSignRecord($userID, $per = self::DEFAULT_PER_PAGE)
    {
        $where = [
            'userID' => $userID
        ];
        $list = self::field('id as dataID,date,num,addTime')->where($where)->order('date asc')->select();
        $list && object2array($list);
        //  签到记录
        $signRecord = $list;
        return [
            'signRecord' => $signRecord,
        ];
    }

    /**
     * 获取签到TXUSD奖励
     * @return mixed
     */
    public static function getSignAward()
    {
        $res = XkSystemRule::where(['rule_code' => 'sign'])->value('coin_num');
        return $res;
    }
}